package com.bahiaapk.dao;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.bahiaapk.dto.TwitterUser;
import com.bahiaapk.util.BahiaUtil;

public class TwitterUserDAO {

	private Context context;
	private SQLiteDatabase database;
	private DBHelper dbHelper;

	public TwitterUserDAO(Context context) {
		this.context = context;
	}

	public TwitterUserDAO openWritable() throws SQLException {
		dbHelper = new DBHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}
	public TwitterUserDAO openReadable() throws SQLException {
		dbHelper = new DBHelper(context);
		database = dbHelper.getReadableDatabase();
		return this;
	}
	

	public void close() {
		dbHelper.close();
	}
	
	public List<TwitterUser> findAll () {
		this.openReadable();

		List<TwitterUser> result = new ArrayList<TwitterUser>();		
		Cursor cursor;
			 
		try{
			cursor = database.rawQuery("select ID, name from tbl_twitter_users", null);
			cursor.moveToFirst();
			
			if (!cursor.isAfterLast()){
				do{
					result.add(this.bindSQLite(cursor));
				}while (cursor.moveToNext());
			}
			
			cursor.close();
		}catch (SQLException e){
			Log.e(BahiaUtil.TAG, e.toString());
		}
		
		this.close();
		
		return result;
	}
	
	private TwitterUser bindSQLite(Cursor cursor){
		TwitterUser twitterMessage  = new TwitterUser();

		for (int i = 0; i < cursor.getColumnCount(); i++){
			if("ID".equals(cursor.getColumnName(i)))
				twitterMessage.setId(cursor.getLong(i));
			else if("name".equals(cursor.getColumnName(i))) 
					twitterMessage.setName(cursor.getString(i));	
		}
		return twitterMessage;
	}
	

}
